<?php

namespace addons\wddj\library;

use app\api\model\wddj\Chat;
use app\api\model\wddj\Message;
use app\api\model\wddj\User;
use app\api\model\wddj\user\Order;
use GatewayWorker\Lib\Gateway;

class Events
{
    public static $clientHeartbeatTimes = [];

    public static function onMessage($client_id, $message)
    {
        try {
            // 解析消息
            $messageArray = json_decode($message, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                Gateway::sendToClient($client_id, json_encode([
                    'type' => 'error',
                    'message' => 'Invalid JSON format'
                ]));
            }

            // 如果是心跳消息
            if (isset($messageArray['type']) && $messageArray['type'] == 'heartbeat') {
                if (empty($messageArray['token'])) {
                    Gateway::sendToClient($client_id, json_encode([
                        'type' => 'error',
                        'message' => 'Token is required'
                    ]));
                }
                // 获取 token 信息
                $tokenInfo = \app\common\library\Token::get($messageArray['token']);
                if (!$tokenInfo) {
                    Gateway::sendToClient($client_id, json_encode([
                        'type' => 'error',
                        'message' => 'Invalid token'
                    ]));
                }
                // 更新客户端的最后心跳时间
                self::$clientHeartbeatTimes[$client_id] = time();

                // 不向客户端发送心跳响应，保持连接
                // 这里只更新心跳时间，不做其他操作
            } else {// 处理其他类型的消息
                // 校验 token
                if (empty($messageArray['token'])) {
                    Gateway::sendToClient($client_id, json_encode([
                        'type' => 'error',
                        'message' => 'Token is required'
                    ]));
                }

                // 获取 token 信息
                $tokenInfo = \app\common\library\Token::get($messageArray['token']);
                if (!$tokenInfo) {
                    Gateway::sendToClient($client_id, json_encode([
                        'type' => 'error',
                        'message' => 'Invalid token'
                    ]));
                }

                // 获取用户微信 ID
                $wechat_id = User::getWechatId($tokenInfo['user_id']);
                if (!$wechat_id) {
                    Gateway::sendToClient($client_id, json_encode([
                        'type' => 'error',
                        'message' => 'Invalid wechat_id'
                    ]));
                }

                // 获取订单信息
                $orderObj = (new Order())->get($messageArray['order_id']);
                if (!$orderObj) {
                    Gateway::sendToClient($client_id, json_encode([
                        'type' => 'error',
                        'message' => 'Order not found'
                    ]));
                }

                // 校验 sender 参数
                if (!in_array($messageArray['sender'], ['user', 'driver'])) {
                    Gateway::sendToClient($client_id, json_encode([
                        'type' => 'error',
                        'message' => 'Invalid sender'
                    ]));
                }

                if (!in_array($wechat_id, [$orderObj['wechat_id'], $orderObj['driver_wechat_id']])) {
                    Gateway::sendToClient($client_id, json_encode([
                        'type' => 'error',
                        'message' => '用户和订单没有关联'
                    ]));
                }


                // 构建聊天数据
                if ($messageArray['sender'] == 'user' && $orderObj['wechat_id'] == $wechat_id) {
                    $chatData = [
                        'order_id' => $messageArray['order_id'],
                        'wechat_id' => $wechat_id,
                        'message' => $messageArray['message'],
                        'sender' => $messageArray['sender'],
                        'driver_wechat_id' => $orderObj['driver_wechat_id'],
                    ];
                    $accept_wechat_id = $orderObj['driver_wechat_id'];
                    $avatar = '/assets/addons/wddj/img/user.png';
                }
                if ($messageArray['sender'] == 'driver' && $orderObj['driver_wechat_id'] == $wechat_id) {
                    $chatData = [
                        'order_id' => $messageArray['order_id'],
                        'driver_wechat_id' => $wechat_id,
                        'message' => $messageArray['message'],
                        'sender' => $messageArray['sender'],
                        'wechat_id' => $orderObj['wechat_id'],
                    ];
                    $accept_wechat_id = $orderObj['wechat_id'];
                    $avatar = '/assets/addons/wddj/img/driver.png';
                }
                if (!empty($chatData)) {
                    // 保存聊天记录
                    $chatModel = new Chat();
                    $chatModel->data($chatData);
                    $chatModel->allowField(true)->save();

                    // 保存消息记录
                    $messageModel = new Message();
                    $messageAddData = [
                        'order_id' => $messageArray['order_id'],
                        'wechat_id' => $accept_wechat_id,
                        'type' => '2',
                        'content' => $messageArray['message'],
                    ];
                    $messageModel->data($messageAddData);
                    $result = $messageModel->allowField(true)->save();

                    if (!$result) {
                        Gateway::sendToClient($client_id, json_encode([
                            'type' => 'error',
                            'message' => 'Failed to save message'
                        ]));
                    }

                    // 格式化时间
                    $current_time = time();
                    $createtime = (date('Y', $current_time) === date('Y')) ? date('m-d H:i', $current_time) : date('Y-m-d H:i', $current_time);

                    // 构建返回消息
                    $new_message = [
                        'message' => $messageArray['message'],
                        'type' => 'onMessage',
                        'result' => 'success',
                        'avatar' => $avatar,
                        'createtime' => $createtime,
                        'sender' => $messageArray['sender'],
                    ];
                    $json_new_message = json_encode($new_message);

                    // 推送消息给用户
                    if ($result) {
                        Gateway::sendToUid($accept_wechat_id, $json_new_message);
                        Gateway::sendToUid($wechat_id, $json_new_message);
                    }
                }
            }
        } catch (\Exception $e) {
            // 捕获异常并记录错误
            error_log($e->getMessage());
            Gateway::sendToClient($client_id, json_encode([
                'type' => 'error',
                'message' => $e->getMessage(),
            ]));
        }
    }




    public static function onWebSocketConnect($client_id, $data)
    {
        if (!isset($data['server']['HTTP_TOKEN'])) {
            Gateway::sendToClient($client_id, json_encode([
                'type' => 'error',
                'message' => 'Token is required'
            ]));
        } else {
            // 获取 token 信息

            $tokenInfo = \app\common\library\Token::get($data['server']['HTTP_TOKEN']);
            if (!$tokenInfo) {
                Gateway::sendToClient($client_id, json_encode([
                    'type' => 'error',
                    'message' => 'Invalid token'
                ]));
            }

            Gateway::sendToClient($client_id, json_encode(array(
                'type'      => 'init',
                'client_id' => $client_id
            )));
        }


    }


    /**
     * 当用户断开连接时触发的方法
     * @param integer $client_id 断开连接的客户端
     * @return void
     */
    public static function onClose($client_id)
    {
        try {
            GateWay::sendToAll("client[$client_id] logout\n");

            // 释放与客户端相wdd关的资源
            Gateway::closeClient($client_id);

        } catch (\Exception $e) {
            // 捕获关闭连接异常并记录
            error_log('Error in onClose: ' . $e->getMessage());
        }
    }


    /**
     * 当进程启动时
     * @param integer $businessWorker 进程实例
     */
    public static function onWorkerStart($businessWorker)
    {
        try {
            echo '进程启动，进程id:' . $businessWorker->id . PHP_EOL;
        } catch (\Exception $e) {
            // 捕获进程启动异常并记录
            error_log('Error in onWorkerStart: ' . $e->getMessage());
        }
    }

    /**
     * 当进程关闭时
     * @param integer $businessWorker 进程实例
     */
    public static function onWorkerStop($businessWorker)
    {
        try {
            echo '进程关闭，进程id:' . $businessWorker->id . PHP_EOL;
        } catch (\Exception $e) {
            // 捕获进程停止异常并记录
            error_log('Error in onWorkerStop: ' . $e->getMessage());
        }
    }


}